package net.xdclass.util;

/**
 * @Classname CustomeList
 * @Description TODO
 * @Date 2022/11/23 20:26
 * @Created by sunhao
 * 自定义集合类
 */
public class CustomList<T> {
  /**
   * 定义集合
   */
  private T[] list;

  /**
   * 该集合有效元素个数
   */
  private int num;

  /**
   * 初始化数组大小 有效元素初始化为0
   *
   * @param size
   */
  public CustomList(int size) {
    this.list = (T[])new Object[size];
    this.num = 0;
  }

  /**
   * 获取元素个数
   */
  public int size() {
    return this.num;
  }

  /**
   * 顺序表的判空
   */
  public boolean isEmpty() {
    return this.num == 0;
  }

  /**
   * 顺序表的判满实现
   */
  public boolean isFull() {
    return this.num == this.list.length;
  }

  /**
   * 添加元素
   */
  public void add(T element) {
    if (this.isFull()) {
      reList(this.list.length*2);
    }
    list[this.num++] = element;
  }

  /**
   * 遍历元素
   */
  public void forEach() {
    for (int i = 0; i < num; i++) {
      System.out.println(this.list[i]);
    }
  }

  /**
   * 指定位置插入元素
   */
  public void add(int index, T element) {
    if (index < 0 || index > num) {
      throw new IllegalArgumentException("参数不合法!");
    }
    if (isFull()) {
      reList(this.list.length*2);
    }

    for (int i = num; i > index; i--) {
      this.list[i] = this.list[i - 1];
    }
    this.list[index] = element;
    num++;
  }

  /**
   * 删除指定位置的元素
   * @param index
   */
  public void remove(int index) {
    if (index < 0 || index > num) {
      throw new IllegalArgumentException("参数不合法!");
    }
    for (int i = 0; i < num -1 ; i++) {
      list[i] = list[i + 1];
    }
    num--;
  }

  public void update(int index, T element){
    list[index] = element;
  }

  public T getIndexElement(int index){
    return list[index];
  }

  /**
   * 扩容
   * @param size
   */
  public void reList(int size){
    T[] temp = list;
    list = (T[]) new Object[size];
    for (int i = 0; i < temp.length; i++) {
      list[i] = temp[i];
    }
  }


  public static void main(String[] args) {
    CustomList<String> customList = new CustomList<>(4);
    customList.add("1");
    customList.add("2");
    customList.add("3");
    customList.add(0, "9");
    customList.remove(0);
    customList.update(0,"5");
    customList.forEach();
  }
}
